import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../api/graphql/product_gql.dart';
import '../widget/async_image.dart';

class Search extends StatefulWidget {
  const Search({super.key});

  @override
  State<Search> createState() => _SearchState();
}

class _SearchState extends State<Search> {
  final TextEditingController _searchController = TextEditingController();
  String? _searchText;

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('搜索页'),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                hintText: '输入商品名称搜索',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.search),
              ),
              onSubmitted: (value) {
                setState(() {
                  _searchText = value;
                });
              },
            ),
          ),
        ),
      ),
      body: _searchText == null
          ? const Center(
        child: Text('请输入关键词搜索商品'),
      )
          : _buildProductList(),
    );
  }

  Widget _buildProductList() {
    return Query<Object?>(
      options: QueryOptions(
        document: gql(ProductGQL.fetchQueryProductList),
        variables: {
          'limit': 20,
          'keyword': _searchText, // 添加搜索关键词变量
        },
      ),
      builder: (QueryResult result, {refetch, fetchMore}) {
        if (result.hasException) {
          return Center(
            child: Text('查询出错: ${result.exception.toString()}'),
          );
        }

        if (result.isLoading) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        // 修正数据路径，使用 queryProductList 而不是 productList
        final products = result.data?['product']['queryProductList']['products'] as List<dynamic>?;

        if (products == null || products.isEmpty) {
          return const Center(
            child: Text('未找到相关商品'),
          );
        }

        return ListView.builder(
          padding: const EdgeInsets.all(8.0),
          itemCount: products.length,
          itemBuilder: (context, index) {
            final product = products[index];
            return Card(
              child: ListTile(
                leading: product['coverAddr'] != null
                    ?    AsyncImageWidget(
                  imageUrl: product['coverAddr'],
                  width: 50,
                  height: 50,
                  fit: BoxFit.cover,
                )
                    : const Icon(Icons.image),
                title: Text(product['title'] ?? '未知商品'),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('价格: ¥${product['price'] ?? '未知'}'),
                    Text('评分: ${product['rate'] ?? '暂无评分'}'),
                  ],
                ),
                onTap: () {
                  // 跳转到商品详情页
                  Navigator.pushNamed(
                    context,
                    '/product_detail',
                    arguments: {
                      'productId': product['id'],
                    },
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}